import {createRouter, createWebHashHistory} from 'vue-router'
import store from '../store/index';

const routes = [
    {
        path: "/",
        redirect: "/MainPage"
    },
    {
        name: "MainPage",
        path: "/MainPage",
        component: () => import("../components/MainPage"),
        meta: { isLogin: false }
    },
    {
        name: "PrivateDataset",
        path: "/PrivateDataset",
        component: () => import("../components/PrivateDataset"),
        meta: { isLogin: true }
    },
    {
        name: "PublicDataset",
        path: "/PublicDataset",
        component: () => import("../components/PublicDataset"),
        meta: { isLogin: false }
    },
    {
        name: "PrivacyStatement",
        path: "/PrivacyStatement",
        component: () => import("../components/PrivacyStatement"),
        meta: { isLogin: false }
    },
    {
        name: "UserLogin",
        path: "/UserLogin",
        component: () => import("../components/UserLogin"),
        meta: { isLogin: false }
    },
    {
        name: "UserSignup",
        path: "/UserSignup",
        component: () => import("../components/UserSignup"),
        meta: { isLogin: false }
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    document.querySelector('body').setAttribute('style', 'margin:0;padding:0')
    if (sessionStorage.getItem("username") != null &&
        sessionStorage.getItem("password") != null) {
        store.commit("login", sessionStorage.getItem("username"), sessionStorage.getItem("password"))
        next()
    }
    else if (!to.meta.isLogin || store.state.isLogin) {
        next()
    } else {
        alert("请先登录再进入")
        next({
            path: '/UserLogin',
        })
    }
})

export default router
